from flask import Flask, request, jsonify
import requests
import string
import json
import logging
from urllib.parse import urlparse, urlunparse

app = Flask(__name__)

# 配置日志记录  
logging.basicConfig(  
    level=logging.INFO,  # 设置日志级别为 DEBUG  
    format='%(asctime)s - %(levelname)s - %(message)s',  # 日志格式  
    handlers=[  
        # logging.FileHandler('app.log'),  # 将日志输出到文件  
        logging.StreamHandler()  # 也输出到控制台  
    ]  
)
# 定义一个接收 POST 请求并转发的路由
@app.route('/forward', methods=['POST'])
def forward_request():
    # 获取原始请求的 JSON 数据
    original_data = request.json

    # 修改数据，这里只是简单地在原始数据中添加一个新的字段
    modified_data = original_data.copy()

    status_ = modified_data['status']
    for alerts_one in modified_data['alerts']:
        severity_ = alerts_one['labels'].get("severity") or ""
        summarycn_ = alerts_one['annotations'].get("summaryCn") or "详情"
        summary_ = alerts_one['annotations'].get("summary") or ""
        # message_ = alerts_one['annotations'].get("message") or ""
        alertname_ = alerts_one['labels'].get("alertname") or ""
        startsat_ = alerts_one.get("startsAt") or ""
        description_ = alerts_one['annotations'].get("description") or ""


        # 构建转发的目标 URL
        target_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=2fe36cd3'  # 替换为实际的目标 URL

        temp_data = {
            "msgtype":"template_card",
            "template_card":{
                "card_type":"text_notice",
                "source":{
                    "icon_url":"http://xn.prd.sumztech.com:65179/favicon.ico",
                    "desc": alertname_,
                    "desc_color":0
                },
                "main_title":{
                    "title": status_,
                    "desc": summary_
                },
                "emphasis_content":{
                    "title": severity_,
                    "desc": "告警级别"
                },
                "quote_area":{
                    "type":1,
                    "url":"http://10.103.32.39:8080/",
                    "appid":"APPID",
                    "pagepath":"PAGEPATH",
                    "title": summarycn_,
                    "quote_text": startsat_
                },
                "sub_title_text": description_,
                "card_action":{
                    "type":1,
                    "url":"http://10.103.32.39:8080/",
                    "appid":"APPID",
                    "pagepath":"PAGEPATH"
                }
            }
        }

        print(temp_data)
        data = json.dumps(temp_data)
        # 发起转发请求
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
            }
        response = requests.post(url=target_url, data=data, headers=header)

        print(response.json())

        # 返回转发请求的响应内容
        return jsonify(response.json())
    

@app.route('/<path:subpath>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
def proxy(subpath):
    # domain = request.headers.get('Host')  # 获取访问的域名

    parsed_url = urlparse(request.url)
    target_url = urlunparse(('https',) + parsed_url[1:])

    # if domain == 'qyapi.weixin.qq.com':
    #     target_url = f'https://qyapi.weixin.qq.com/{subpath}'
    # else:
    #     return 'Domain not supported', 400

    response = requests.request(
        method=request.method,
        url=target_url,
        headers={key: value for (key, value) in request.headers if key != 'Host'},
        data=request.get_data(),
        cookies=request.cookies,
        allow_redirects=False,
        verify=False
    )

    logging.info(f"地址: {target_url}") 

    excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
    headers = [(name, value) for (name, value) in response.raw.headers.items() if name.lower() not in excluded_headers]

    return response.content, response.status_code, headers


if __name__ == '__main__':
    app.run(debug=True, port=8888)